const { Service } = require('egg');
const { getSqlCount, getSqlSelect } = require('../utils/sql')


class UserService extends Service {
  async getSqlUserList(param, type = 'get') {
    return await this.app.mysql[type]('user_list', param)
  }

  // 登录
  async login(param) {
    const result = await this.getSqlUserList({
      user_name: param.user_name
    })
    if (result && param.password === result.password) {
      const token = this.app.jwt.sign({
        id: result.id,
        username: result.user_name,
        exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60)
      }, this.app.config.jwt.secret)
      return {
        isOk: true,
        data: Object.assign({}, result, { token })
      }
    }
    return { isOk: false }
  }
  // 创建用户
  async create(param) {
    const userData = await this.getSqlUserList({ user_name: param.user_name });
    if (userData) return false // 确保用户名唯一
    const nParam = Object.assign({}, param, {
      create_time: new Date().valueOf()
    })
    const result = await this.getSqlUserList(nParam, 'insert');
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }
  // 更新用户
  async update(param) {
    const nParam = Object.assign({}, param, {
      update_time: new Date().valueOf()
    })
    const result = await this.getSqlUserList(nParam, 'update')
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }
  // 删除用户
  async delete(param) {
    if (!param.id) return false
    const result = await this.getSqlUserList({ id: param.id }, 'delete');
    const updateSuccess = result.affectedRows === 1;
    return updateSuccess
  }

  // 分页查询
  async select(param) {
    const where = {
      user_name: {
        type: 'like',
        val: param.user_name
      },
      phone: {
        type: 'like',
        val: param.phone
      },
      create_time: {
        type: 'range',
        val: param.create_time
      }
    }
    Object.keys(where).forEach(key => {
      if (!where[key].val) {
        delete where[key]
      }
    })
    const countSql = getSqlCount('user_list', { where })
    const countList = await this.app.mysql.query(countSql)
    const count = countList[0]['count(1)']
    const sql = getSqlSelect('user_list', {
      where,
      orders: [[ 'create_time', 'desc' ]],
      limit: param.pageSize, // 返回数据量
      offset: param.current, // 数据偏移量
    })
    console.log(sql)
    const result = await this.app.mysql.query(sql)
    return {
      total: count,
      list: result
    };
  }
}

module.exports = UserService;
